<script setup>
import { computed, ref, useSlots, watch } from 'vue'
import { JBoltApi } from '@/service/request'

const slots = useSlots()
const props = defineProps({
    url: {
        type: String,
        required: true
    },
    value: {
        type: [String, Number, Boolean],
        default: undefined
    },
    confirm: String,
    fieldName: {
        type: String,
        default: 'enable'
    }
})

const emit = defineEmits(['update:value', 'change'])

const finalValue = computed(() => {
    if (typeof props.value == 'string') {
        return props.value == 'true' || props.value == '1'
    }
    if (typeof props.value == 'number') {
        return props.value != 0
    }
    return !!props.value
})
const loading = ref(false)
// watch(
//     () => props.value,
//     (newV) => {
//         if (newV !== finalValue.value) {
//             finalValue.value = !!newV
//         }
//     }
// )

async function change(value) {
    if (loading.value) return

    //如果配置了confirm，则需要确认
    if (props.confirm) {
        let yes = await new Promise((resolve) => {
            window.$dialog?.warning({
                title: '确认',
                content: props.confirm,
                positiveText: '确认',
                negativeText: '取消',
                onPositiveClick: () => {
                    resolve(true)
                },
                onNegativeClick: () => {
                    resolve(false)
                }
            })
        })
        if (!yes) {
            return
        }
    }

    const urlGet = new Function('value', 'return `' + props.url + '`')
    loading.value = true

    try {
        const { error, result } = await JBoltApi.get(urlGet(value))
        if (error) return
        if (typeof result.data == 'boolean') {
            //返回的是最新的enable值
            emit('update:value', result.data)
        } else if (result?.data?.[props.fieldName] !== undefined) {
            //返回的是最新的完整数据
            emit('update:value', result.data[props.fieldName])
        } else {
            emit('update:value', value)
        }
        emit('change', result.data)
    } finally {
        loading.value = false
    }
}
</script>

<template>
    <n-switch :loading="loading" :value="finalValue" @update:value="change">
        <template v-for="(_item, key) in slots" :key="key" #[key]="data">
            <slot :name="key" v-bind="data ?? {}" />
        </template>
    </n-switch>
</template>

<style scoped></style>
